<?php
/**
 * Created by PhpStorm.
 * User: Fenn
 * Date: 2018/6/3
 * Time: 7:51
 */
namespace App\Controllers;


use App\Models\Group;
use App\Models\Role_user_group;
use App\Models\User;
use Illuminate\Database\Capsule\Manager;
use Psr\Container\ContainerInterface;
use Slim\Http\Request;
use Slim\Http\Response;
use Respect\Validation\Validator as v;

class UserController extends BaseController{

    /**ddd**/
    /**
     * @var  Manager
     */
    protected $DB;
    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);
        $this->DB = $this->container->db;
    }

    public function index(Request $request,Response $respone){
        $params = $request->getParsedBody();
        $page     = isset($params['page']) ? $params['page']  : 1;
        $pageSize = isset($params['pagesSize']) ? $params['pagesSize'] : 10;
        $offset   = ($page - 1) * $pageSize;
        if(!is_numeric($page) || !is_numeric($pageSize)) {
            return $this->json(1005,'数据不合法');
        }
        $offset = ($page - 1) * $pageSize;

        $token = $this->getToken($request);
        $user  = User::where('token',$token)->first();
        $group = Group::where(['pid'=>$user->group_id,['id','<>',$user->group_id]])->select('id')->get()->toArray();

        $grouplist = [];
        foreach ($group as $item){
            $grouplist[] = $item['id'];
        }
        $total = $user = User::whereIn('group_id',$grouplist)->count();
        $user = User::select(['id','username','phone','email','created_at','updated_at','status'])
                ->whereIn('group_id',$grouplist)
                ->get()
                ->toArray();
        foreach ($user as $key=>$val) {
            if($val['status'] == 1) {
                $user[$key]['status_str'] = "启用";
            }else {
                $user[$key]['status_str'] = "禁用";
            }
        }
        $data['total'] = $total;
        $data['list']  = $user;
        return $this->jsonWithData(1,'ok',$data);
    }

    public function store(Request $request,Response $response){
        $data       = $request->getParams();
        $user = new User();
        if(isset($data['userid'])){
            $validation = $this->validateUpdate($data);
            if($validation->failed()){
                return $response->withJson(['error'=>['参数错误！']],422);
            }
            $ret = $user->where("id",$data['userid'])->update(
                [
                    'username'=> $this->clean_xss($data['username']),
                    'phone'   => $this->clean_xss($data['phone']),
                    'email'   => $this->clean_xss($data['email']),
                    'status'  => $this->clean_xss($data['status']),

                ]
            );
            if($ret!==false){
                return $response->withJson(['error'=>['success']]);
            }else {
                return $response->withJson(['error' => ['failed']], 422);
            }
        }else{
            $validation = $this->validateInsert($data);
            if($validation->failed()){
                $errors = $validation->getErrors();
                foreach ($errors as $item){
                    $message = $item[0];
                    break;
                }
                return $this->json(1005,$message);
            }
            $this->DB::beginTransaction();
            try {
                $salt = str_random(4);
                $user->username     = $this->clean_xss($data['username']);
                $user->email        = $this->clean_xss($data['email']);
                $user->phone        = $this->clean_xss($data['phone']);
                $user->group_id     = $this->clean_xss($data['group_id']);
                $user->salt         = $salt;
                $user->password     = md5(md5($data['password']).$salt);
                $user->status       = 1;
                $user->code         = '';
                $user->code_expire  = '';
                $user->token        = '';
                $user->token_expire = '';
                $user->save();

                $role_user_group = new Role_user_group();
                $role_user_group->group_id = $data['group_id'];
                $role_user_group->role_id  = $data['role_id'];
                $role_user_group->user_id  = $user->id;
                $role_user_group->save();
                $this->DB::commit();
                return $this->json(1,"OK");
            } catch (Exception $e){
                $this->DB::rollback();
                throw $e;
                return $this->json(0,"注册失败！");
            }
        }
    }

    public function delete(Request $request) {
        $parmas = $request->getParams();
        if(!isset($parmas['userid']) || intval($parmas['userid'])==0){
            return $this->json("1005","请选择要删除的记录");
        }
        $ret = User::where('id',$parmas['userid'])->delete();
        if($ret){
            return $this->json(1,"OK");
        }else {
            return $this->json(0,"删除失败！");
        }
    }

    public function userStatusChange(Request $request){
        $params =$request->getParsedBody();
        $validation = $this->container->validator->validateArray($params,
            ["userid" =>v::noWhitespace()->notEmpty()->numeric(),
                "status" =>v::noWhitespace()->numeric()]
        );
        if($validation->failed()){
            return $this->json(1005,"参数错误");
        }
        $ret = User::where('id',$params['userid'])->update(['status'=>$params['status']]);
        if($ret){
            return $this->json(1,"OK");
        }else{
            return $this->json(0,"修改失败");
        }

    }

    protected function validateInsert($values){
        return $this->container->validator->validateArray($values,
            [
                'username'=> v::noWhitespace()->notEmpty()->existsInTable($this->container->db->table('user'), 'phone')->setTemplate('同手机号码用户已被存在或是用户名为空'),
                'phone'   => v::noWhitespace()->phone()->notEmpty()->existsInTable($this->container->db->table('user'), 'phone')->setTemplate('同手机号码用户已被存在或手机号填写错误'),
                'email'   => v::noWhitespace()->email()->notEmpty()->existsInTable($this->container->db->table('user'), 'email')->setTemplate('同Email用户已被存在或是Email填写错误'),
            ]);
    }

    protected function validateUpdate($values){
        return $this->container->validator->validateArray($values,
            [
                'username'=> v::noWhitespace()->notEmpty()->setTemplate('请填写用户名'),
                'phone'   => v::noWhitespace()->phone()->notEmpty()->setTemplate('请正确填写手机号码'),
                'email'   => v::noWhitespace()->email()->notEmpty()->setTemplate("请正确填写邮箱地址"),
            ]);
    }

}
